package com.hisan.freeride.home.activity;

import android.Manifest;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.pm.PackageManager;
import android.net.Uri;
import android.os.Bundle;
import android.provider.Settings;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;

import com.hisan.freeride.R;
import com.hisan.freeride.common.base.AppConfig;
import com.hisan.freeride.common.base.BaseActivity;
import com.hisan.freeride.common.callback.DialogCallback;
import com.hisan.freeride.common.utils.CollectionUtils;
import com.hisan.freeride.common.utils.utils.MyHandlerUtil;
import com.hisan.freeride.databinding.LookReleaseBinding;
import com.hisan.freeride.home.adapter.LookReserveAdapter;
import com.hisan.freeride.home.model.LookRelease;
import com.jwenfeng.library.pulltorefresh.BaseRefreshListener;
import com.lzy.okgo.OkGo;

import java.util.ArrayList;
import java.util.List;

/**
 * 创建时间 : 2017/6/6
 * 创建人：yangyingqi
 * 公司：嘉善和盛网络有限公司
 * 备注：司机查看预约乘客列表页面
 */
public class LookReleaseActivity extends BaseActivity<LookReleaseBinding> {
    private LookReserveAdapter adapter;
    //广播
    private InnerBroadcastReceiver receiver;
    //拨打电话权限返回码
    private static final int MY_PERMISSIONS_REQUEST_CALL_PHONE = 1;
    private String phone="";
    private  int did;
    private int page=1;
    private List<LookRelease> lookReleases=new ArrayList<>();

    @Override
    protected int getLayoutId() {
        return R.layout.look_release;
    }
    @Override
    protected void initView() {
        mBinding.setStateModel(mStateModel);
        adapter=new LookReserveAdapter(new ArrayList<>(0));
        mBinding.rv.setAdapter(adapter);
        mBinding.rv.setLayoutManager(new LinearLayoutManager(this));
        Bundle bundle=getIntent().getExtras();
        if (!CollectionUtils.isNullOrEmpty(bundle)){
            did=bundle.getInt("id");
        }
        registerReceiver();
    }

    @Override
    protected void initEvent() {
        mBinding.topBack.setOnClickListener(v -> finishActivity(true));
        mBinding.pull.setRefreshListener(new BaseRefreshListener() {
            @Override
            public void refresh() {
                page=1;
                lookReleases.clear();
                loadData(true);
                mBinding.pull.finishRefresh();
            }

            @Override
            public void loadMore() {
                page++;
                loadData(true);
                mBinding.pull.finishLoadMore();
            }
        });
    }

    @Override
    protected void loadData(boolean isRefresh) {
        OkGo.<List<LookRelease>>get(AppConfig.Triporderlist)
                .tag(this)
                .params("page",page)
                .params("size",20)
                .params("id",did)
                .execute(new DialogCallback<List<LookRelease>>(this){
                    @Override
                    public void onSuccess(com.lzy.okgo.model.Response<List<LookRelease>> response) {
                        super.onSuccess(response);
                        if (!CollectionUtils.isNullOrEmpty(response.body())){
                            showData();
                            if(response.body().size()>=20){
                                mBinding.pull.setCanLoadMore(true);
                            }else {
                                mBinding.pull.setCanLoadMore(false);
                            }
                            lookReleases.addAll(response.body());
                            adapter.setNewData(lookReleases);
                        }else {
                            if (!CollectionUtils.isNullOrEmpty(lookReleases)){
                                adapter.setNewData(lookReleases);
                            }else noData();
                        }
                    }

                    @Override
                    public void onError(com.lzy.okgo.model.Response<List<LookRelease>> response) {
                        super.onError(response);
                        showErrorView(response.code());
                    }
                });

    }


    //注册广播接收者
    private void registerReceiver(){
        IntentFilter filter = new IntentFilter();
        filter.addAction("cancel");
        filter.addAction("ok");
        filter.addAction("phone");
        receiver = new InnerBroadcastReceiver();
        registerReceiver(receiver,filter);
    }


    class InnerBroadcastReceiver extends BroadcastReceiver {
        @Override
        public void onReceive(Context context, Intent intent) {
            String action = intent.getAction();
            int id = intent.getIntExtra("id", -1);
            if ("cancel".equals(action)) {
                Setreview(id, 2);
            } else if ("ok".equals(action)) {
                Setreview(id, 1);
            } else if ("phone".equals(action)) {
                phone = intent.getStringExtra("phone");
                if (!CollectionUtils.isNullOrEmpty(phone)) {
                    getmDialog("是否打开手机拨号","取消","确定").show();
                }
            }
        }
    }

    //审核用户行程订单
    private void Setreview(int id,int state) {
        OkGo.put(AppConfig.Setreview)
                .tag(this)
                .params("id",id)
                .params("state",state)
                .execute(new DialogCallback<Object>(this){
                    @Override
                    public void onSuccess(com.lzy.okgo.model.Response<Object> response) {
                        super.onSuccess(response);
                        if (!CollectionUtils.isNullOrEmpty(response.body())){
                            if (isOk(response)){
                                page=1;
                                lookReleases.clear();
                                MyHandlerUtil.getHandler().postDelayed(() -> loadData(true),200);
                            }else{
                                showError(response);
                            }
                        }
                    }

                    @Override
                    public void onError(com.lzy.okgo.model.Response<Object> response) {
                        super.onError(response);
                        showError(response);
                    }
                });
    }

    @Override
    public void onOk() {
        super.onOk();
        // 检查是否获得了权限（Android6.0运行时权限）
        if (ContextCompat.checkSelfPermission(LookReleaseActivity.this,
                Manifest.permission.CALL_PHONE) != PackageManager.PERMISSION_GRANTED) {
            // 没有获得授权，申请授权
            if (ActivityCompat.shouldShowRequestPermissionRationale(LookReleaseActivity.this,
                    Manifest.permission.CALL_PHONE)) {
                // 弹窗需要解释为何需要该权限，再次请求授权
                showToast("请在应用中开启电话权限");
                // 帮跳转到该应用的设置界面，让用户手动授权
                Intent intent = new Intent(Settings.ACTION_APPLICATION_DETAILS_SETTINGS);
                Uri uri = Uri.fromParts("package", getPackageName(), null);
                intent.setData(uri);
                startActivity(intent);
            } else {
                // 不需要解释为何需要该权限，直接请求授权
                ActivityCompat.requestPermissions(LookReleaseActivity.this,
                        new String[]{Manifest.permission.CALL_PHONE},
                        MY_PERMISSIONS_REQUEST_CALL_PHONE);
            }
        } else {
            // 已经获得授权，可以打电话
            if (!CollectionUtils.isNullOrEmpty(phone)) {

                CallPhone(phone);
            }
        }
    }

    private void CallPhone(String number) {
        if (CollectionUtils.isNullOrEmpty(number)) {
            showToast("号码不能为空！");
        } else {
            // 拨号：激活系统的拨号组件
            Intent intent = new Intent(); // 意图对象：动作 + 数据
            intent.setAction(Intent.ACTION_CALL); // 设置动作
            Uri data = Uri.parse("tel:" + number); // 设置数据
            intent.setData(data);
            startActivity(intent); // 激活Activity组件
        }
    }

    // 处理权限申请的回调
    @Override
    public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
        switch (requestCode){
            case MY_PERMISSIONS_REQUEST_CALL_PHONE: {
                if (grantResults.length > 0
                        && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                    // 授权成功，继续打电话
                    if (!CollectionUtils.isNullOrEmpty(phone))
                        CallPhone(phone);
                } else {
                    showToast("电话授权失败！");
                }
                break;
            }
        }
    }
}
